package yiran.depositcumulative.lister;

import org.black_ixx.playerpoints.event.PlayerPointsChangeEvent;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import yiran.depositcumulative.data.DatabaseService;
import yiran.depositcumulative.output.Logger;

import java.lang.reflect.Method;
import java.util.UUID;

public class PointsListener implements Listener {
    private final DatabaseService databaseService;

    public PointsListener(DatabaseService databaseService) {
        this.databaseService = databaseService;
    }

    @EventHandler
    public void onPointsChange(PlayerPointsChangeEvent event) {
        if (event.getChange() > 0) {
            String playerName = getPlayerNameFromEvent(event);

            if (playerName == null || playerName.isEmpty()) {
                Logger.error("无法获取玩家名，跳过记录");
                return;
            }

            int points = event.getChange();
            databaseService.recordDeposit(playerName, points);

            // 获取当前累计值并记录
            int total = databaseService.getTotalDeposit(playerName);
            Logger.info("记录玩家 " + playerName + " 充值: " + points + " 点券 (累计: " + total + ")");
        }
    }

    private String getPlayerNameFromEvent(PlayerPointsChangeEvent event) {
        try {
            // 新版本API：通过UUID获取玩家名
            Method getPlayerIdMethod = event.getClass().getMethod("getPlayerId");
            UUID uuid = (UUID) getPlayerIdMethod.invoke(event);
            OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
            return player.getName();
        } catch (NoSuchMethodException e) {
            // 旧版本API：直接获取玩家名
            try {
                Method getUsernameMethod = event.getClass().getMethod("getUsername");
                return (String) getUsernameMethod.invoke(event);
            } catch (Exception ex) {
                Logger.error("获取玩家名失败: " + ex.getMessage());
                return "UnknownPlayer";
            }
        } catch (Exception e) {
            Logger.error("处理玩家名时出错: " + e.getMessage());
            return "ErrorPlayer";
        }
    }

}

